/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.tenancy.core.extensions;

import io.iec.edp.caf.data.source.DataSourceIdentifierResolver;
import io.iec.edp.caf.tenancy.api.context.MultiTenantContextInfo;
import io.iec.edp.caf.tenancy.api.entity.DbConnectionInfo;
import io.iec.edp.caf.tenancy.core.context.MultiTenantContextHolder;

/**
 * 数据源标识解析接口，Hibernate的MultiTenantIdentifierResolver转调此接口
 * @author wangyandong
 * @date 2021/08/17 17:41
 *
 */
public class TenantDataSourceIdentifierResolverImpl implements DataSourceIdentifierResolver {

    /**
     * 解析数据源标识符
     *
     * @return
     */
    @Override
    public String resolveDataSourceIdentifier() {
        MultiTenantContextInfo multiTenantContextInfo = MultiTenantContextHolder.get();

        if(multiTenantContextInfo.isMasterDb())
        {
            return TenantDataSourceProvider.MASTERDB;
        }

        DbConnectionInfo dbConnectionInfo = multiTenantContextInfo.getDbConnectionInfo();

        if (dbConnectionInfo == null)
        {
            //上下文不存在租户时，直接返回主库
            Integer tenantId = multiTenantContextInfo.getTenantId();
            if(tenantId<=0)
                return TenantDataSourceProvider.MASTERDB;
            return tenantId  + "," + multiTenantContextInfo.getAppCode()  + "," + multiTenantContextInfo.getServiceUnit();
        }
        else
        {
            return dbConnectionInfo.getDbType() + "," +dbConnectionInfo.getConnectionString();
        }
    }
}
